const mysql = require('mysql2');
require('dotenv').config();

const connection = mysql.createConnection({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '123456',
  database: process.env.DB_NAME || 'store_db'
});

connection.connect((err) => {
  if (err) {
    console.error('数据库连接失败:', err);
    return;
  }
  
  console.log('✅ 数据库连接成功');
  
  // 获取所有表名
  connection.query('SHOW TABLES', (err, tables) => {
    if (err) {
      console.error('获取表列表失败:', err);
      return;
    }
    
    console.log('\n📋 当前数据库中的表:');
    tables.forEach((table, index) => {
      const tableName = table[`Tables_in_${process.env.DB_NAME || 'store_db'}`];
      console.log(`${index + 1}. ${tableName}`);
    });
    
    console.log('\n📝 详细表结构:');
    console.log('='.repeat(80));
    
    let processedTables = 0;
    const totalTables = tables.length;
    
    tables.forEach((table) => {
      const tableName = table[`Tables_in_${process.env.DB_NAME || 'store_db'}`];
      
      // 获取表结构
      connection.query(`SHOW CREATE TABLE ${tableName}`, (err, result) => {
        if (err) {
          console.error(`获取表 ${tableName} 结构失败:`, err);
        } else {
          console.log(`\n-- 表: ${tableName}`);
          console.log(result[0]['Create Table']);
          console.log('');
        }
        
        processedTables++;
        if (processedTables === totalTables) {
          console.log('='.repeat(80));
          console.log('✅ 数据库结构导出完成');
          
          // 获取一些示例数据
          console.log('\n📊 示例数据:');
          getSampleData(tables, 0);
        }
      });
    });
  });
});

function getSampleData(tables, index) {
  if (index >= tables.length) {
    connection.end();
    return;
  }
  
  const tableName = tables[index][`Tables_in_${process.env.DB_NAME || 'store_db'}`];
  
  connection.query(`SELECT COUNT(*) as count FROM ${tableName}`, (err, countResult) => {
    if (err) {
      console.error(`获取表 ${tableName} 数据量失败:`, err);
      getSampleData(tables, index + 1);
      return;
    }
    
    const count = countResult[0].count;
    console.log(`${tableName}: ${count} 条记录`);
    
    if (count > 0) {
      connection.query(`SELECT * FROM ${tableName} LIMIT 2`, (err, sampleData) => {
        if (!err && sampleData.length > 0) {
          console.log(`  示例数据:`, JSON.stringify(sampleData[0], null, 2));
        }
        getSampleData(tables, index + 1);
      });
    } else {
      getSampleData(tables, index + 1);
    }
  });
}